<template>
  <div class="app-container">
    <el-form :model="queryParam" ref="queryForm" :inline="true">
      <el-form-item label="试卷名称：">
        <el-autocomplete
          v-model="queryParam.paperName"
          :fetch-suggestions="querySearch"
          placeholder="请输入试卷名称"
          clearable
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="年级：">
        <el-select
          v-model="queryParam.level"
          placeholder="年级"
          @change="levelChange"
          clearable
          @clear="clearLevel"
        >
          <el-option
            v-for="item in levelEnum"
            :key="item.key"
            :value="item.key"
            :label="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学科：">
        <el-select v-model="queryParam.subjectId" clearable>
          <el-option
            v-for="item in subjectFilter"
            :key="item.id"
            :value="item.id"
            :label="item.name + ' ( ' + item.levelName + ' )'"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户名">
        <el-autocomplete
          v-model="queryParam.createUser"
          :fetch-suggestions="querySearchUser"
          placeholder="请输入用户名"
          clearable
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select v-model="queryParam.status" clearable>
          <el-option
            v-for="item in statusEnum"
            :key="item.key"
            :value="item.key"
            :label="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      @sort-change="changeTableSort"
      style="width: 100%"
    >
      <el-table-column prop="id" label="Id" width="100" />
      <el-table-column prop="paperName" label="试卷名称" />
      <el-table-column prop="userName" label="用户名称" width="200px" />
      <el-table-column prop="gradeLevel" label="年级" width="100px">
        <template slot-scope="{ row }">
          {{ gradeLevelFormatter(row.gradeLevel) }}
        </template>
      </el-table-column>
      <el-table-column
        label="得分"
        width="100px"
        :sortable="'custom'"
        prop="userScore"
      >
        <template slot-scope="{ row }">
          {{ row.userScore }} / {{ row.paperScore }}
        </template>
      </el-table-column>
      <el-table-column label="题目对错" width="80px">
        <template slot-scope="{ row }">
          {{ row.questionCorrect }} / {{ row.questionCount }}
        </template>
      </el-table-column>
      <el-table-column
        prop="doTime"
        label="耗时"
        width="100px"
        :sortable="'custom'"
      />
      <el-table-column
        prop="createTime"
        label="提交时间"
        width="160px"
        :sortable="'custom'"
      />
      <el-table-column label="状态" prop="status" width="100px">
        <template slot-scope="{ row }">
          <el-tag :type="statusTagFormatter(row.status)">
            {{ statusTextFormatter(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="140px">
        <template slot-scope="{ row }">
          <router-link
            :to="{ path: '/answer/paper/edit', query: { id: row.id } }"
            v-if="row.status === 1"
          >
            <el-button type="danger" size="small">批改</el-button>
          </router-link>
          <router-link
            :to="{ path: '/answer/paper/read', query: { id: row.id } }"
            v-if="row.status === 2"
          >
            <el-button type="primary" size="small">查看试卷</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParam.pageIndex"
      :limit.sync="queryParam.pageSize"
      @pagination="search"
    />
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions } from "vuex";
import Pagination from "@/components/Pagination";
import examPaperAnswerApi from "@/api/examPaperAnswer";
import subjectApi from "@/api/subject";
import userApi from "@/api/user";

export default {
  components: { Pagination },
  data() {
    return {
      queryParam: {
        level: null,
        subjectId: null,
        paperName: null,
        pageIndex: 1,
        pageSize: 10,
        status: null,
        sort: "id desc",
        createUser: "",
      },
      queryUserParam: {
        userName: "",
        role: 1,
        pageIndex: 1,
        pageSize: 20000,
      },
      users: null,
      userFilter: null,
      subjects: null,
      subjectFilter: null,
      userList: [],
      listLoading: false,
      tableData: [],
      total: 0,
    };
  },
  mounted() {
    // this.initSubject();
    this.$nextTick(() => {
      subjectApi.list().then((re) => {
        this.subjects = re.response;
        this.subjectFilter = this.subjects;
      });
      userApi.getUserPageList(this.queryUserParam).then((re) => {
        this.users = re.response.list;
        this.users.map((item) => {
          item.value = item.userName;
        });
        this.userFilter = this.users;
      });
      this.initPaperNameList();
      this.search();
    });
  },
  methods: {
    changeTableSort(column) {
      //获取字段名称和排序类型
      var fieldName = column.prop;
      var sortingType = column.order;
      this.queryParam.pageIndex = 1;
      let x = "";
      if (fieldName == "userScore") {
        x = "user_score";
      } else if (fieldName == "createTime") {
        x = "create_time";
      } else if (fieldName == "doTime") {
        x = "do_time";
      }
      if (sortingType == "descending") {
        this.queryParam.sort = x + " desc";
      } else {
        this.queryParam.sort = x + " asc";
      }
      this.search();
    },
    querySearch(queryString, cb) {
      var paperNameList = this.paperNameList;
      var results = queryString
        ? paperNameList.filter(this.createFilter(queryString))
        : paperNameList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    querySearchUser(queryString, cb) {
      var userFilter = this.userFilter;
      var results = queryString
        ? userFilter.filter(this.createFilter(queryString))
        : userFilter;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (item) => {
        return (
          item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    search() {
      this.listLoading = true;
      let param = JSON.parse(JSON.stringify(this.queryParam));

      if (param.createUser) {
        this.users.map((user) => {
          if (param.createUser === user.userName) {
            param.createUser = user.id;
          }
        });
      }
      examPaperAnswerApi
        .page(param)
        .then((data) => {
          const re = data.response;
          this.tableData = re.list;
          this.total = re.total;
          this.queryParam.pageIndex = re.pageNum;
          this.listLoading = false;
        })
        .catch((e) => {
          this.listLoading = false;
        });
    },
    submitForm() {
      this.queryParam.pageIndex = 1;
      this.search();
    },
    levelChange() {
      this.queryParam.subjectId = null;
      this.subjectFilter = this.subjects.filter(
        (data) => data.level === this.queryParam.level
      );
      this.queryParam.createUser = null;
      this.userFilter = this.users.filter(
        (data) => data.userLevel === this.queryParam.level
      );
    },
    clearLevel() {
      this.subjectFilter = this.subjects;
      this.userFilter = this.users;
    },
    statusTagFormatter(status) {
      return this.enumFormat(this.statusTag, status);
    },
    statusTextFormatter(status) {
      return this.enumFormat(this.statusEnum, status);
    },
    gradeLevelFormatter(status) {
      return this.enumFormat(this.levelEnum, status);
    },
    ...mapActions("exam", {
      initSubject: "initSubject",
      initPaperNameList: "initPaperNameList",
    }),
  },
  computed: {
    ...mapGetters("enumItem", ["enumFormat"]),
    ...mapGetters("exam", ["subjectEnumFormat"]),
    //...mapState("exam", { subjects: (state) => state.subjects,}),
    ...mapState("enumItem", {
      statusEnum: (state) => state.exam.examPaperAnswer.statusEnum,
      statusTag: (state) => state.exam.examPaperAnswer.statusTag,
      levelEnum: (state) => state.user.levelEnum,
    }),
    ...mapState("exam", {
      paperNameList: (state) => state.paperNameList,
    }),
  },
};
</script>
